package com.easemob.helpdesk.activity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.easemob.helpdesk.utils.FileUtils;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.net.ApiService;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by xiaolong.wei on 2019/6/24.
 */

public class MySignContractActivity extends BaseActivityV2 {
    private static final String TAG = "MySignContractActivity";

    public static final int SIGN_CONTRACT_REQUEST = 1;


    @Override
    protected void initFindView() {

        back=findViewById(R.id.back);
        progressBar=findViewById(R.id.progressBar);
        web=findViewById(R.id.web);
        loading=findViewById(R.id.loading);
        button=findViewById(R.id.button);
        noContent=findViewById(R.id.no_content);
        back.setOnClickListener(view -> finish());
        button.setOnClickListener(view -> {
            if ("UNSIGNED".equals(status)){
                showDialog("请您确认是否同意签约协议中的所有条款\n点击下方\"确认签约\"后立即生效");
            }else if ("SIGNED".equals(status)){
                downloadContract();
            }
        });

    }

    LinearLayout back;
    ProgressBar progressBar;
    WebView web;
    TextView button;
    ProgressBar loading;
    TextView noContent;

    private String status;
    private int shopId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_sign_contract_activity);
        initFindView();
        init();
    }

    private void init() {
        status = getIntent().getStringExtra("status");
        shopId = getIntent().getIntExtra("shopId",-1);
        if ("UNSIGNED".equals(status)){//未签约
            button.setText("同意上述所有条款");
            button.setTextColor(Color.WHITE);
            button.setBackgroundColor(Color.parseColor("#EA5404"));
            button.setVisibility(View.VISIBLE);
        }else if ("SIGNED".equals(status)){//已签约
            button.setTextColor(Color.parseColor("#5DBAFD"));
            button.setText("已签约，点击下载协议");
            button.setBackgroundResource(R.drawable.grey_top_border_white_bg);
            button.setVisibility(View.VISIBLE);
        }
        web.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
            }
        });

        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                progressBar.setProgress(newProgress);
            }

        });

        WebSettings settings = web.getSettings();
        settings.setJavaScriptEnabled(true);
        getDetailContract();
    }

/*    @OnClick({R.id.back, R.id.button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.button:
                if ("UNSIGNED".equals(status)){
                    showDialog("请您确认是否同意签约协议中的所有条款\n点击下方\"确认签约\"后立即生效");
                }else if ("SIGNED".equals(status)){
                    downloadContract();
                }
                break;
//            case R.id.right_button:
//                openAssignFolder("/storage/emulated/0/housekeeper_resource");
//                break;
        }
    }*/

    private void showDialog(String msg) {
        Intent intent = new Intent();
        intent.setClass(this, AlertDialog.class);
        intent.putExtra("msg", msg);
        intent.putExtra("okString", "确定");
        intent.putExtra("cancelString", "取消");
        startActivityForResult(intent, SIGN_CONTRACT_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == SIGN_CONTRACT_REQUEST) {
            loading.setVisibility(View.VISIBLE);
            signContract();
        }
    }

    private void getDetailContract() {
        ApiService apiService = HKHttpUtils.getApiService();
        apiService.getConstractDetail(MainActivity.ticket).enqueue(new HKResponseResultCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                if (!TextUtils.isEmpty(s)) {
                    progressBar.setVisibility(View.VISIBLE);
                    loading.setVisibility(View.GONE);
                    noContent.setVisibility(View.GONE);
                    web.loadDataWithBaseURL(null, s, "text/html", "UTF-8", null);
//                    web.loadData(s, "text/html", "utf-8");
                    web.setVisibility(View.VISIBLE);
                } else {
                    loading.setVisibility(View.GONE);
                    noContent.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                Toast.makeText(MySignContractActivity.this,msg,Toast.LENGTH_LONG).show();
                loading.setVisibility(View.GONE);
                noContent.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailed(Call call, Throwable t) {
                Toast.makeText(MySignContractActivity.this,"网络连接异常，请稍后再试",Toast.LENGTH_LONG).show();
                loading.setVisibility(View.GONE);
                noContent.setVisibility(View.VISIBLE);
            }
        });
    }

    private void signContract(){
        ApiService apiService = HKHttpUtils.getApiService();
        apiService.signContract(MainActivity.ticket,shopId).enqueue(new HKResponseResultCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                loading.setVisibility(View.GONE);

                button.setTextColor(Color.parseColor("#5DBAFD"));
                button.setText("已签约，点击下载协议");
                button.setBackgroundResource(R.drawable.grey_top_border_white_bg);
                button.setVisibility(View.VISIBLE);
                status = "SIGNED";
                Toast.makeText(MySignContractActivity.this,"签约成功",Toast.LENGTH_LONG).show();
                MainApplication.getInstance().getEventEmitter().sendEvent("update_sign_contract");
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                loading.setVisibility(View.GONE);
                Toast.makeText(MySignContractActivity.this,msg,Toast.LENGTH_LONG).show();
                MainApplication.getInstance().getEventEmitter().sendEvent("update_sign_contract");
            }

            @Override
            public void onFailed(Call call, Throwable t) {
                loading.setVisibility(View.GONE);
                Toast.makeText(MySignContractActivity.this,"网络连接异常，请稍后重试",Toast.LENGTH_LONG).show();
                MainApplication.getInstance().getEventEmitter().sendEvent("update_sign_contract");
            }
        });
    }


    private void downloadContract(){
        Intent intent = new Intent(this,ProgressDialogActivity.class);
        intent.putExtra("shopId",shopId);
        startActivity(intent);
    }

    private void openAssignFolder(String path){

        try {
            Uri uri = null;
            if (Build.VERSION.SDK_INT >= 24) {
                uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()+".provider",new File(path));
            } else {
                uri = Uri.fromFile(new File(path));
            }
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(uri, "*/*");
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
